

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/IKKIS_LOGO.png">
  <link rel="icon" href="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/IKKIS_LOGO.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Ikki">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. package.json是如何产生的1.1 npm initnpm init 命令用来初始化一个简单的 package.json 文件，执行该命令后终端会依次询问 name, version, description 等字段。  npm init 默认执行行为 我们在执行 npm init 的时候,会有一个初始化 pacakge.json 过程，然后一路回车，其实可以直接使用 npm ini">
<meta property="og:type" content="article">
<meta property="og:title" content="npm介绍和package.json解析">
<meta property="og:url" content="http://81.68.132.127/2022/09/22/npm/npm%E4%BB%8B%E7%BB%8D%E5%92%8Cpackage-json%E8%A7%A3%E6%9E%90/index.html">
<meta property="og:site_name" content="IKKI">
<meta property="og:description" content="1. package.json是如何产生的1.1 npm initnpm init 命令用来初始化一个简单的 package.json 文件，执行该命令后终端会依次询问 name, version, description 等字段。  npm init 默认执行行为 我们在执行 npm init 的时候,会有一个初始化 pacakge.json 过程，然后一路回车，其实可以直接使用 npm ini">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/beijing/iTab-2ed16y.jpeg">
<meta property="article:published_time" content="2022-09-22T09:42:15.000Z">
<meta property="article:modified_time" content="2022-10-07T12:05:19.414Z">
<meta property="article:author" content="Ikki">
<meta property="article:tag" content="前端工程化">
<meta property="article:tag" content="npm">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/beijing/iTab-2ed16y.jpeg">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>npm介绍和package.json解析 - IKKI</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="/fluid/css/fluid-extention.css">
<link rel="stylesheet" href="/fluid/css/nihao.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"81.68.132.127","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":3},"lazyload":{"enable":true,"loading_img":"https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 100vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Ikki-BUG制造者</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('http://image.ikki0603.cn') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="npm介绍和package.json解析"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-09-22 17:42" pubdate>
          2022年9月22日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          78 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
        <div class="scroll-down-bar">
          <i class="iconfont icon-arrowdown"></i>
        </div>
      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">npm介绍和package.json解析</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2022年10月7日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="1-package-json是如何产生的"><a href="#1-package-json是如何产生的" class="headerlink" title="1. package.json是如何产生的"></a>1. package.json是如何产生的</h1><h2 id="1-1-npm-init"><a href="#1-1-npm-init" class="headerlink" title="1.1 npm init"></a>1.1 npm init</h2><p>npm init 命令用来初始化一个简单的 package.json 文件，执行该命令后终端会依次询问 name, version, description 等字段。</p>
<ul>
<li>npm init 默认执行行为<ul>
<li>我们在执行 npm init 的时候,会有一个初始化 pacakge.json 过程，然后一路回车，其实可以直接使用 npm init –yes 在命令后追加 –yes 参数即可，其作用与一路回车相同，这样生成的文件中就包含 package.json 文件</li>
</ul>
</li>
<li>自定义 npm init 行为<ul>
<li>npm init 命令的原理并不复杂，调用 shell 脚本，输出一个初始化的 package.json 文件。所以相应地，自定义 npm init 命令的实现方式也很简单，在电脑 npmStudy 目录创建一个 .npm-init.js 即可，该文件的 module.exports 即为 package.json 配置内容，需要获取用户输入时候，使用 prompt() 方法即可。例如编写这样的 ~/.npm-init.js</li>
</ul>
</li>
</ul>
<p>还有一句命令需要执行 npm config set init-module ./npm-init.js 呀！</p>
<figure class="highlight stylus"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-echcorlacl5vpe"></i><span>stylus</span><div class="collapse show" id="collapse-echcorlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs stylus">const desc = <span class="hljs-built_in">prompt</span>(<span class="hljs-string">&#x27;description?&#x27;</span>, <span class="hljs-string">&#x27;A new package...&#x27;</span>)<br>const bar = <span class="hljs-built_in">prompt</span>(<span class="hljs-string">&#x27;bar?&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>)<br>const count = <span class="hljs-built_in">prompt</span>(<span class="hljs-string">&#x27;count?&#x27;</span>, <span class="hljs-string">&#x27;42&#x27;</span>)<br><br>module<span class="hljs-selector-class">.exports</span> = &#123;<br>  key: <span class="hljs-string">&#x27;value&#x27;</span>,<br>  foo: &#123;<br>    bar: bar,<br>    count: count<br>  &#125;,<br>  name: <span class="hljs-built_in">prompt</span>(<span class="hljs-string">&#x27;name?&#x27;</span>, process<span class="hljs-selector-class">.cwd</span>()<span class="hljs-selector-class">.split</span>(<span class="hljs-string">&#x27;/&#x27;</span>)<span class="hljs-selector-class">.pop</span>()),<br>  version: <span class="hljs-built_in">prompt</span>(<span class="hljs-string">&#x27;version?&#x27;</span>, <span class="hljs-string">&#x27;0.1.0&#x27;</span>),<br>  description: desc,<br>  <span class="hljs-selector-tag">main</span>: <span class="hljs-string">&#x27;index.js&#x27;</span>,<br>&#125;<br></code></pre></td></tr></table></div></figure>
<ul>
<li>然后在 /npmStudy 目录下执行 npm init</li>
<li>然后生成 package.json 文件。到这里一个 npm init 简单自定义过程结束,知道了两种生成 pacakge.json 的方式<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/npm/ikki-2022-04-05-21-33-15.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><h1 id="2-package-json-中的常规属性"><a href="#2-package-json-中的常规属性" class="headerlink" title="2.package.json 中的常规属性"></a>2.package.json 中的常规属性</h1><h2 id="2-1-npm的依赖包"><a href="#2-1-npm的依赖包" class="headerlink" title="2.1 npm的依赖包"></a>2.1 npm的依赖包</h2>这里只说我们常用的两个依赖包  dependenices 和 devDependenices,其它的一些依赖包只有作为包的发布者才会用到，需要的小伙伴自行查看文档。<h3 id="2-1-1-dependenices-生产环境"><a href="#2-1-1-dependenices-生产环境" class="headerlink" title="2.1.1 dependenices(生产环境)"></a>2.1.1 dependenices(生产环境)</h3>通过命令npm install/i packageName -S/–save把包装在此依赖项里。如果没有指定版本，直接写一个包的名字，则安装当前npm仓库中这个包的最新版本。如果要指定版本的，可<figure class="highlight excel"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-u7pz7qlacl5vpe"></i><span>excel</span><div class="collapse show" id="collapse-u7pz7qlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs excel">npm i lodash@<span class="hljs-number">4.17</span>.<span class="hljs-number">13</span> -S 指定版本号<br>=&gt;<br><span class="hljs-string">&quot;dependencies&quot;</span><span class="hljs-symbol">:</span> &#123;<br>     <span class="hljs-string">&quot;lodash&quot;</span><span class="hljs-symbol">:</span> <span class="hljs-string">&quot;4.17.13&quot;</span>,<br>     <span class="hljs-string">&quot;moment&quot;</span><span class="hljs-symbol">:</span> <span class="hljs-string">&quot;^2.24.0&quot;</span>,<br>&#125;<br></code></pre></td></tr></table></div></figure>
<h3 id="2-1-2-devDependenices-开发环境"><a href="#2-1-2-devDependenices-开发环境" class="headerlink" title="2.1.2 devDependenices(开发环境)"></a>2.1.2 devDependenices(开发环境)</h3><figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-cr9z4dlacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-cr9z4dlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;devDependencies&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>     <span class="hljs-attr">&quot;jest&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;^24.3.1&quot;</span><span class="hljs-punctuation">,</span><br>     <span class="hljs-attr">&quot;eslint&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;^6.1.0&quot;</span><span class="hljs-punctuation">,</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></div></figure>
<h3 id="2-1-3-二者简单对比"><a href="#2-1-3-二者简单对比" class="headerlink" title="2.1.3 二者简单对比"></a>2.1.3 二者简单对比</h3></li>
<li>devDependencies=&gt;本地开发,dependencies=&gt;开发+线上</li>
<li>(-D或者–save-dev) 会添加到 devDependencies 里面，(-S或者–save)会添加到 dependencies</li>
<li>从npm 5.x开始，如果什么参数都不带，那么默认添加到 dependencies 中</li>
</ul>
<h2 id="2-2-bin"><a href="#2-2-bin" class="headerlink" title="2.2 bin"></a>2.2 bin</h2><figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-srnjw9lacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-srnjw9lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;bin&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>   <span class="hljs-attr">&quot;vm2&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;./bin/vm2&quot;</span><br><span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br></code></pre></td></tr></table></div></figure>
<ul>
<li>bin 字段指定了各个内部命令对应的可执行文件的位置。如果全局安装模块报，npm 会使用符号链接把可执行文件链接到 /usr/local/bin，如果项目中安装，会链接到  <code>./node_modules/.bin/</code></li>
<li>上面的这种当你的包安装到全局时：npm 会在 <code>/usr/local/bin</code> 下创建一个以 vm2 为名字的软链接，指向全局安装下来的 vm2 包下面的 <code>&quot;./bin/index.js&quot;</code>。这时你在命令行执行 vm2 则会调用链接到的这个 js 文件。</li>
</ul>
<h2 id="2-3-main"><a href="#2-3-main" class="headerlink" title="2.3 main"></a>2.3 main</h2><p>一个常用的npm包</p>
<figure class="highlight css"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-tppzhwlacl5vpe"></i><span>css</span><div class="collapse show" id="collapse-tppzhwlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs css">&#123;<br>  &quot;<span class="hljs-selector-tag">main</span>&quot;: <span class="hljs-string">&quot;lib/index.js&quot;</span>,<br>&#125;<br></code></pre></td></tr></table></div></figure>
<p>main 属性指定程序的主入口文件，其他项目在引用这个 npm 包时，实际上引入的是 lib/index 中暴露出去的模块。</p>
<h2 id="2-4-script"><a href="#2-4-script" class="headerlink" title="2.4 script"></a>2.4 script</h2><h3 id="2-4-1-什么是-npm-script-脚本"><a href="#2-4-1-什么是-npm-script-脚本" class="headerlink" title="2.4.1 什么是 npm script 脚本?"></a>2.4.1 什么是 npm script 脚本?</h3><p>在生成的 package.json 文件中，有一个 scripts 对象，在这个对象中，npm 允许使用 scripts 字段定义脚本命令。</p>
<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-4ftx8alacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-4ftx8alacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;scripts&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;test&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;test.js&quot;</span><br>    <span class="hljs-attr">&quot;build&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;tsc&quot;</span><span class="hljs-punctuation">,</span><br><span class="hljs-punctuation">&#125;</span><span class="hljs-punctuation">,</span><br></code></pre></td></tr></table></div></figure>
<ul>
<li>scripts 对象中每一个属性，对应一段脚本。比如，test 命令对应的脚本是 node test.js。</li>
<li>命令行下使用 npm run 命令，就可以执行这段脚本。</li>
<li>查看当前项目的所有 npm 脚本命令，可以使用不带任何参数的npm run命令。<h4 id="2-4-1-1-原理"><a href="#2-4-1-1-原理" class="headerlink" title="2.4.1.1 原理"></a>2.4.1.1 原理</h4>我们每次在运行 scripts 中的一个属性时候(npm run),实际系统都会自动新建一个shell(一般是Bash)，在这个shell里面执行指定的脚本命令。因此 凡是能在 shell 中允许的脚本，都可以写在npm scripts中。</li>
</ul>
<blockquote>
<p>特别的点，npm run 新建的 shell，会在当前目录的 node_modules/.bin 子目录加入到 PATH 变量，执行结束后，再将 PATH 变量恢复原样。也就是说，当前项目目录 node——modules/.bin 子目录中所有的脚本，都可以直接用脚本名称调用，不需要增加路径.（简单总结：通过 npm 启动的脚本，会默认把 node_modules/.bin 加到 PATH 环境变量中。）</p>
</blockquote>
<h4 id="2-4-1-2例子"><a href="#2-4-1-2例子" class="headerlink" title="2.4.1.2例子"></a>2.4.1.2例子</h4><p>当前项目的依赖里面有 Mocha，只要直接写 mocha test 就可以了。</p>
<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-57urrwlacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-57urrwlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;test&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;mocha test&quot;</span><br></code></pre></td></tr></table></div></figure>
<p>而不用写成下面这样。</p>
<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-dlsu85lacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-dlsu85lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;test&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;./node_modules/.bin/mocha test&quot;</span><br></code></pre></td></tr></table></div></figure>
<ul>
<li>然后我们就可以直接执行 npm run test 了。npm 脚本的退出码，也遵守 Shell 脚本规则。如果退出码不是0，npm 就认为这个脚本执行失败。</li>
<li>这里有的小伙伴可能会有疑问，node_modules目录下的.bin文件是哪里来的?我之前也有这样的疑问，打开了一个 .bin/tsc,里面的内容是这样的<figure class="highlight javascript"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-lx3zu5lacl5vpe"></i><span>javascript</span><div class="collapse show" id="collapse-lx3zu5lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-meta">#!/usr/bin/env node</span><br><span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;../lib/tsc.js&#x27;</span>)<br></code></pre></td></tr></table></div></figure></li>
<li>npm install 安装的某个模块，如果模块在 package.json 中配置了 bin 属性，在安装时候会自动软链接到 node_modules/.bin 中，举个例子：如 mocha 源码 配置了：<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-axgypplacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-axgypplacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;mocha&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;bin&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;mocha&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;./bin/mocha&quot;</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></div></figure>
<h4 id="2-4-1-3-script脚本默认值"><a href="#2-4-1-3-script脚本默认值" class="headerlink" title="2.4.1.3 script脚本默认值"></a>2.4.1.3 script脚本默认值</h4></li>
<li>正常情况下，npm 脚本是用户自己定义。但是 npm 本身对两个脚本提供了默认值，这两个脚本不用在 script 属性中定义，可以直接使用<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-e5qd12lacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-e5qd12lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;start&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;node server.js&quot;</span><br><span class="hljs-attr">&quot;install&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;node-gyp rebuild&quot;</span><br></code></pre></td></tr></table></div></figure></li>
<li>npm run start 的默认值是 node server.js ，前提是根目录下有 server.js 这个脚本</li>
<li>npm run install 的默认值是 node-gyp rebuild，前提是根目录下有 binding.gyp 文件</li>
</ul>
<h3 id="2-4-2-钩子-生命周期"><a href="#2-4-2-钩子-生命周期" class="headerlink" title="2.4.2 钩子(生命周期)"></a>2.4.2 钩子(生命周期)</h3><ul>
<li>好多语言或者框架我们学的时候都会考虑到生命周期，其实 package.json 中的 script 也是有生命周期的。npm 脚本有两个钩子，pre 和 post，当我们执行start脚本时候，start 的钩子就是 prestart 和 poststart。</li>
<li>当我们执行 npm run start 的时候，npm 会自动按照下面的顺序执行<figure class="highlight routeros"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-lq9xtclacl5vpe"></i><span>routeros</span><div class="collapse show" id="collapse-lq9xtclacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">npm <span class="hljs-built_in">run</span> prestart &amp;&amp; npm <span class="hljs-built_in">run</span> start &amp;&amp; npm <span class="hljs-built_in">run</span> poststart<br></code></pre></td></tr></table></div></figure></li>
<li>那这个钩子有什么用呢，在实际开发中，我们可以做一些准备或者清理工作，下面是个例子(引用的阮一峰老师文章中的例子)<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-rtl6aolacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-rtl6aolacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;clean&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;rimraf ./dist &amp;&amp; mkdir dist&quot;</span><span class="hljs-punctuation">,</span><br><span class="hljs-attr">&quot;prebuild&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;npm run clean&quot;</span><span class="hljs-punctuation">,</span><br><span class="hljs-attr">&quot;build&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;cross-env NODE_ENV=production webpack&quot;</span><br></code></pre></td></tr></table></div></figure>
<blockquote>
<p>钩子好用，但是不可乱用，举个开发过程中遇到的坑，有一次想设置运行时的环境变量，当时想优雅一点，就在 prestart 里面设置了一个环境变量，但是在项目 start 的时候，无法拿到设置的环境变量，因为 script 的属性运行的时候都会新启动一个 shell，所以在 prestart中设置的环境变量只对应了那个shell的运行时。</p>
</blockquote>
</li>
</ul>
<h3 id="2-4-3-env环境变量"><a href="#2-4-3-env环境变量" class="headerlink" title="2.4.3 env环境变量"></a>2.4.3 env环境变量</h3><ul>
<li>我们在执行 npm run 脚本时候, npm 会设置一些特殊的env环境变量。其中package.json中的所有字段，都会被设置为以npm_package_开头的环境变量。看个简单的例子<figure class="highlight prolog"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-lc1z8tlacl5vpe"></i><span>prolog</span><div class="collapse show" id="collapse-lc1z8tlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs prolog">&#123;<br>  <span class="hljs-string">&quot;name&quot;</span>: <span class="hljs-string">&quot;npm-demo&quot;</span>,<br>  <span class="hljs-string">&quot;version&quot;</span>: <span class="hljs-string">&quot;1.0.0&quot;</span>,<br>  <span class="hljs-string">&quot;script&quot;</span>: &#123;<br>    <span class="hljs-string">&quot;build&quot;</span>: <span class="hljs-string">&quot;webpack --mode=production&quot;</span><br>  &#125;,<br>  <span class="hljs-string">&quot;files&quot;</span>: [<span class="hljs-string">&quot;src&quot;</span>]<br>&#125;<br></code></pre></td></tr></table></div></figure></li>
<li>可以得到 npm_package_name、npm_package_version、npm_package_script_build、npm_package_files_0等变量。注意上面 package.json 中对象和数组中每个字段都会有对应的环境变量。</li>
<li>同时，npm 相关的所有配置也会被设置为以npm_config_开头的环境变量。此外，还会设置一个比较特殊的环境变量npm_lifecycle_event，表示正在运行的脚本名称。</li>
<li>比如执行npm run serve 的时候，process.env.npm_lifecycle_event值为serve，通过判断这个变量，可以将一个脚本使用在不同的npm scripts中。这里还要提一下上面说的钩子，npm_lifecycle_event可以和钩子配合使用，利用这个变量，在同一个脚本文件里面，为不同的 npm scripts 命令编写代码。请看下面的例子。<figure class="highlight arcade"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-adfxw6lacl5vpe"></i><span>arcade</span><div class="collapse show" id="collapse-adfxw6lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs arcade">const TARGET = process.env.npm_lifecycle_event;<br><br><span class="hljs-keyword">if</span> (TARGET === <span class="hljs-string">&#x27;service&#x27;</span>) &#123;<br>  <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">`Running the service task!`</span>);<br>&#125;<br><br><span class="hljs-keyword">if</span> (TARGET === <span class="hljs-string">&#x27;preservice&#x27;</span>) &#123;<br>  <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">`Running the preservice task!`</span>);<br>&#125;<br><br><span class="hljs-keyword">if</span> (TARGET === <span class="hljs-string">&#x27;postservice&#x27;</span>) &#123;<br>  <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">`Running the postservice task!`</span>);<br>&#125;<br></code></pre></td></tr></table></div></figure>
<blockquote>
<p>强调：这些环境变量只能在 npm run 的脚本执行环境内拿到，正常执行的 node 脚本是获取不到的。所以，不能直接通过 env $npm_package_name 的形式访问，但可以在 scripts 中定义脚本”scripts”: {“bundle”: “echo $npm_package_name”}来访问。</p>
</blockquote>
</li>
<li>环境变量常用小技巧<figure class="highlight dockerfile"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-92olg2lacl5vpe"></i><span>dockerfile</span><div class="collapse show" id="collapse-92olg2lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs dockerfile"><span class="hljs-keyword">env</span> 命令可以列出所有环境变量<br>npm <span class="hljs-keyword">run</span><span class="language-bash"> <span class="hljs-built_in">env</span></span><br></code></pre></td></tr></table></div></figure>
<figure class="highlight dos"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-yb9lmelacl5vpe"></i><span>dos</span><div class="collapse show" id="collapse-yb9lmelacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs dos">在shell脚本中输出环境变量<br><span class="hljs-built_in">echo</span> <span class="hljs-built_in">PATH</span><br></code></pre></td></tr></table></div></figure>
<figure class="highlight gauss"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-bc6tfulacl5vpe"></i><span>gauss</span><div class="collapse show" id="collapse-bc6tfulacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs gauss">在 <span class="hljs-built_in">shell</span> 脚本设置环境变量<br>echo PATH = /usr/<span class="hljs-keyword">local</span>/<span class="hljs-keyword">lib</span><br></code></pre></td></tr></table></div></figure>
<figure class="highlight awk"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-qcxm3wlacl5vpe"></i><span>awk</span><div class="collapse show" id="collapse-qcxm3wlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs awk">有的时候我们需要设置的环境变量是相对项目的再补充一个shell脚本中设置环境变量时候如何拼接相对路径<br>echo PATH = <span class="hljs-variable">$&#123;pwd&#125;</span><span class="hljs-regexp">/lib/i</span>nclude  <span class="hljs-regexp">//</span>使用<span class="hljs-variable">$&#123;&#125;</span>,也可以直接使用双引号<br></code></pre></td></tr></table></div></figure>
<h3 id="2-4-4-脚本传入参数"><a href="#2-4-4-脚本传入参数" class="headerlink" title="2.4.4 脚本传入参数"></a>2.4.4 脚本传入参数</h3></li>
<li>说到脚本传入参数，需要再次提到前面说的 pacakge.json 中的 bin 字段，bin 字段指定了各个内部命令对应的可执行文件的位置。前面已经说了 bin 文件的产生，有了 bin 字段，在安装这个模块的时候，node_modules 下面的 .bin/文件夹 下会有对应模块的文件，和模块中的文件相同，然后我们就可以通过调用这个文件脚本中的方法传入参数了</li>
</ul>
<p>在我的 node_module 中找到一个简单 .bin/文件 下的脚本，大家感受一下。</p>
<figure class="highlight javascript"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-4m4wszlacl5vpe"></i><span>javascript</span><div class="collapse show" id="collapse-4m4wszlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-meta">#!/usr/bin/env node</span><br><span class="hljs-meta">&#x27;use strict&#x27;</span>;<br><span class="hljs-keyword">var</span> pkg = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./package.json&#x27;</span>);<br><span class="hljs-keyword">var</span> osName = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./&#x27;</span>);<br><span class="hljs-keyword">var</span> argv = process.<span class="hljs-property">argv</span>;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">help</span>(<span class="hljs-params"></span>) &#123;<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>([<br>  <span class="hljs-string">&#x27;&#x27;</span>,<br>  <span class="hljs-string">&#x27;  &#x27;</span> + pkg.<span class="hljs-property">description</span>,<br>  <span class="hljs-string">&#x27;&#x27;</span>,<br>  <span class="hljs-string">&#x27;  Example&#x27;</span>,<br>  <span class="hljs-string">&#x27;    os-name&#x27;</span>,<br>  <span class="hljs-string">&#x27;    OS X Mavericks&#x27;</span><br> ].<span class="hljs-title function_">join</span>(<span class="hljs-string">&#x27;\n&#x27;</span>));<br>&#125;<br><br><span class="hljs-keyword">if</span> (argv.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">&#x27;--help&#x27;</span>) !== -<span class="hljs-number">1</span>) &#123;<br> <span class="hljs-title function_">help</span>();<br> <span class="hljs-keyword">return</span>;<br>&#125;<br><br><span class="hljs-keyword">if</span> (argv.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">&#x27;--version&#x27;</span>) !== -<span class="hljs-number">1</span>) &#123;<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pkg.<span class="hljs-property">version</span>);<br> <span class="hljs-keyword">return</span>;<br>&#125;<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">osName</span>());<br></code></pre></td></tr></table></div></figure>
<ul>
<li>node 处理 scripts 中的参数，除了属性后面的第一个命令，以空格分割的任何字符串(除特别shell语法)都是参数，并且都能通过 process.argv 属性访问。<blockquote>
<p>process.argv 属性返回一个数组，数组包含了启动 node 进程时的命令行参数。第一个元素为启动 node 进程的可执行文件的绝对路径名 process.execPath,第二个元素为当前执行的 jacascript 文件路径。剩余的元素为其他命令行参数。</p>
</blockquote>
</li>
<li>比如下面 script 例子<figure class="highlight json"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-tcggiflacl5vpe"></i><span>json</span><div class="collapse show" id="collapse-tcggiflacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-attr">&quot;scripts&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-punctuation">&#123;</span><br>  <span class="hljs-attr">&quot;serve&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;vue-cli-service serve --mode=dev --mobile -config build/example.js&quot;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></div></figure></li>
<li>当我们执行 npm run server 命令的时候，process.argv 的具体内容为：<figure class="highlight scheme"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-iarltslacl5vpe"></i><span>scheme</span><div class="collapse show" id="collapse-iarltslacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs scheme">[ <span class="hljs-symbol">&#x27;/usr/local/Cellar/node/12.14.1/bin/node</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;/Users/mac/Vue-projects/hao-cli/node_modules/.bin/vue-cli-service</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;serve</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;--mode=dev</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;--mobile</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;-config</span>&#x27;,<br>  <span class="hljs-symbol">&#x27;build/example.js</span>&#x27;]<br></code></pre></td></tr></table></div></figure>
再列举几个传参可能有的方式<figure class="highlight arduino"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-qy9l1ulacl5vpe"></i><span>arduino</span><div class="collapse show" id="collapse-qy9l1ulacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs arduino">npm run serve --params  <span class="hljs-comment">// 参数params将转化成process.env.npm_config_params = true</span><br>npm run serve --params=<span class="hljs-number">123</span> <span class="hljs-comment">// 参数params将转化成process.env.npm_config_params = 123</span><br>npm run serve -params  <span class="hljs-comment">// 等同于--params参数</span><br><br>npm run serve -- --params  <span class="hljs-comment">// 将--params参数添加到process.env.argv数组中</span><br>npm run serve params  <span class="hljs-comment">// 将params参数添加到process.env.argv数组中</span><br>npm run serve -- params  <span class="hljs-comment">// 将params参数添加到process.env.argv数组中</span><br></code></pre></td></tr></table></div></figure></li>
<li>对比下 npm install koa2 –save 是不是知道了bin脚本中接收到的 process.env.npm_config_save = true;</li>
</ul>
<h3 id="2-4-5-执行顺序"><a href="#2-4-5-执行顺序" class="headerlink" title="2.4.5 执行顺序"></a>2.4.5 执行顺序</h3><ul>
<li>npm 脚本执行多任务分为两种情况<ul>
<li>并行任务(同时的平行执行)，使用&amp;符号<figure class="highlight routeros"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-unwll9lacl5vpe"></i><span>routeros</span><div class="collapse show" id="collapse-unwll9lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">npm <span class="hljs-built_in">run</span> script1.js &amp; npm <span class="hljs-built_in">run</span> script2.js<br></code></pre></td></tr></table></div></figure></li>
<li>串行任务(前一个任务成功，才执行下一个任务)，使用 &amp;&amp; 符号<figure class="highlight routeros"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-l9017olacl5vpe"></i><span>routeros</span><div class="collapse show" id="collapse-l9017olacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">npm <span class="hljs-built_in">run</span> script1.js &amp;&amp; npm <span class="hljs-built_in">run</span> script2.js<br></code></pre></td></tr></table></div></figure>
<h3 id="2-4-6-任意脚本"><a href="#2-4-6-任意脚本" class="headerlink" title="2.4.6 任意脚本"></a>2.4.6 任意脚本</h3></li>
</ul>
</li>
<li>我们配置的脚本命令，如 “start”: “node test.js”，node test.js 会当做一行代码传递给系统的 shell 去解释执行。实际使用的 shell 可能会根据系统平台而不同，类 UNIX 系统里，如 macOS 或 linux 中指代的是 /bin/sh， 在 windows 中使用的是 cmd.exe。原理我们也看了，因为交给 shell 去解释执行的，说明配置的脚本可以是任意能够在 shell 中运行的命令，而不仅仅是 node 脚本或者 js 代码。如果你的系统里安装了 python（或者说系统变量 PATH里能找到 python 命令），你也可以将 scripts 配置为 “myscript”: “python xxx.py”</li>
</ul>
<h2 id="2-5-npm配置"><a href="#2-5-npm配置" class="headerlink" title="2.5 npm配置"></a>2.5 npm配置</h2><ul>
<li>npm的配置操作可以帮助我们预先设定好npm对项目的行为动作，也可以让我们预先定义好一些配置项以供项目中使用。所以了解npm的配置机制也是很有必要。<h3 id="2-5-1-npm-config"><a href="#2-5-1-npm-config" class="headerlink" title="2.5.1 npm config"></a>2.5.1 npm config</h3></li>
<li>npm cli 提供了 npm config 命令进行 npm 相关配置，通过 npm config ls -l 可查看 npm 的所有配置，包括默认配置。</li>
<li><a target="_blank" rel="noopener" href="https://docs.npmjs.com/misc/config">npm文档页</a>为每个配置项提供了详细的说明 .</li>
<li>修改配置的命令为 npm config set, 我们使用相关的常见重要配置:<ul>
<li>proxy, https-proxy: 指定 npm 使用的代理</li>
<li>registry 指定 npm 下载安装包时的源，默认为 <a target="_blank" rel="noopener" href="https://registry.npmjs.org/">https://registry.npmjs.org/</a> 可以指定为私有 Registry 源</li>
<li>package-lock 指定是否默认生成 package-lock 文件，建议保持默认 true</li>
<li>save true/false 指定是否在 npm install 后保存包为 dependencies, npm 5 起默认为 true</li>
</ul>
</li>
<li>删除指定的配置项命令为 npm config delete <key>.</li>
<li>这里最常见的一个操作是 npm 太慢，设置淘宝镜像<figure class="highlight arduino"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-j1j17qlacl5vpe"></i><span>arduino</span><div class="collapse show" id="collapse-j1j17qlacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs arduino">npm config set registry https:<span class="hljs-comment">//registry.npm.taobao.org</span><br></code></pre></td></tr></table></div></figure></li>
<li>恢复使用之前的 npm<figure class="highlight arduino"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-j4i9j2lacl5vpe"></i><span>arduino</span><div class="collapse show" id="collapse-j4i9j2lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs arduino">npm config set registry https:<span class="hljs-comment">//registry.npmjs.org</span><br></code></pre></td></tr></table></div></figure>
<h3 id="2-5-2-npmrc文件"><a href="#2-5-2-npmrc文件" class="headerlink" title="2.5.2 npmrc文件"></a>2.5.2 npmrc文件</h3></li>
<li>除了使用 CLI 的 npm config 命令显示更改 npm 配置，还可以通过 npmrc 文件直接修改配置。</li>
<li>这样的 npmrc 文件优先级由高到低包括：<ul>
<li>工程内配置文件: /path/to/my/project/.npmrc</li>
<li>用户级配置文件: ~/.npmrc</li>
<li>全局配置文件: $PREFIX/etc/npmrc (即npm config get globalconfig 输出的路径)</li>
<li>npm内置配置文件:/path/to/npm/npmrc</li>
</ul>
</li>
<li>很多时候我们在公司内网需要通过代理才能访问npm源，通过这个机制，我们可以方便地在工程跟目录创建一个 .npmrc 文件来共享需要在团队间共享的 npm 运行相关配置。比如如果我们在公司内网环境下需通过代理才可访问 registry.npmjs.org 源，或需访问内网的 registry, 就可以在工作项目下新增 .npmrc 文件并提交代码库。<figure class="highlight awk"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-429hm2lacl5vpe"></i><span>awk</span><div class="collapse show" id="collapse-429hm2lacl5vpe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs awk">proxy = http:<span class="hljs-regexp">//</span>proxy.example.com/<br>https-proxy = http:<span class="hljs-regexp">//</span>proxy.example.com/<br>registry = http:<span class="hljs-regexp">//</span>registry.example.com/<br></code></pre></td></tr></table></div></figure></li>
<li>因为项目级 .npmrc 文件的作用域只在本项目下，所以在非本目录下，这些配置并不生效。对于使用笔记本工作的开发者，可以很好地隔离公司的工作项目、在家学习研究项目两种不同的环境。</li>
<li>将这个功能与 ~/.npm-init.js 配置相结合，可以将特定配置的 .npmrc 跟 .gitignore, README 之类文件一起做到 npm init 脚手架中，进一步减少手动配置。</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" class="category-chain-item">前端工程化</a>
  
  
    <span>></span>
    
  <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/npm/" class="category-chain-item">npm</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">#前端工程化</a>
      
        <a href="/tags/npm/">#npm</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>npm介绍和package.json解析</div>
      <div>http://81.68.132.127/2022/09/22/npm/npm介绍和package-json解析/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Ikki</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年9月22日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2022年10月7日</div>
        </div>
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/09/22/npm/npm%E5%8C%85%E5%8F%91%E5%B8%83/" title="npm包发布">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">npm包发布</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/09/22/npm/nrm%E4%BB%8B%E7%BB%8D/" title="nrm介绍">
                        <span class="hidden-mobile">nrm介绍</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments" lazyload>
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"6KzYWc2oaEBaHgNl4UIicMJC-gzGzoHsz","appKey":"vJ4FIwKeHRmHraCJraAsjyZ7","path":"window.location.pathname","placeholder":"请输入你的评论\n昵称为必填项目(输入QQ号码可以自动获取昵称和邮箱)\n虽然email不是必选，但是填写了email可以收到推送通知哦！","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":true,"recordIP":true,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":true},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
      IKKI-专业BUG开发
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="/fluid/js/star.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
